<template>
  <div class="w-full h-full pos-relative" id="shareCanvas">
    <canvas
      canvas-id="drawCanvas"
      id="drawCanvas"
      :style="{ width: cvsSize.width, height: cvsSize.height }"
    ></canvas>
    <canvas
      class="pos-absolute top-0 left-0"
      canvas-id="QrCodeCanvas"
      id="QrCodeCanvas"
      style="width: 88px; height: 88px; opacity: 0"
    ></canvas>
  </div>
</template>

<script setup lang="ts">
import UQRCode from 'uqrcodejs' // npm install uqrcodejs
import { platform } from '@/utils/platform'
defineOptions({
  name: 'shared',
  components: {
    UQRCode,
  },
})
const emits = defineEmits(['success'])
const canvasId = 'drawCanvas'
const _this = getCurrentInstance()
let ctx: UniApp.CanvasContext
const cvsSize: any = ref({ width: '100%', height: '100%' })
onMounted(() => {})
onLoad(() => {
  // drawCanvas()
})
const props: any = defineProps({
  propData: {
    type: Object,
    default: {},
  },
})
let setTimeout$: any = null
watch(
  () => props.propData,
  (newVal: any, oldVal: any) => {
    if (JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
      setTimeout$ = setTimeout(() => {
        ResolveData()
      }, 100)
    }
  },
)
let drawIndex: any = 0
const ResolveData = () => {
  const originData: any = props.propData
  if (originData) {
    Promise.all([LoadImage(originData.pic), LoadOuterDom('#shareCanvas')]).then((res: any) => {
      const img: any = res[0]
      const dom: any = res[1]
      const width: any = dom.width
      const imgWidth: any = img.width
      const imgHeight: any = img.height
      const scale: any = imgWidth / imgHeight
      const newWidth: any = width - grid.left - grid.right
      let newHeight: any = Math.round(newWidth / scale)
      let allHeight1: any = 0
      let allHeight2: any = 0
      allHeight1 += newHeight
      allHeight2 += newHeight
      drawIndex = 1
      if (originData.desc) {
        const lineSize: any = Math.ceil(
          originData.desc.split('').length / Math.floor(desc.width / desc.size),
        )
        DrawCanvas.lineSize = lineSize
        const descHeight: any = lineSize * desc.line + desc.top
        allHeight1 += descHeight
        drawIndex++
      }
      if (originData.avatar) {
        const avaterHight: any = avatar.size + avatar.top
        allHeight1 += avaterHight
        drawIndex++
      }
      if (originData.price) {
        const priceHeight: any = price.size + price.top
        allHeight1 += priceHeight
        drawIndex++
      }
      if (originData.qrcode) {
        const qrcodeHight: any = qrcode.size + qrcode.top + 10 + 12
        allHeight2 += qrcodeHight
        drawIndex++
      }
      if (originData.name) {
        drawIndex++
      }
      allHeight1 = allHeight1 + grid.top + grid.bottom
      allHeight2 = allHeight2 + grid.top + grid.bottom
      const allHeight: any = Math.max(allHeight1, allHeight2)
      const allWidth: any = width
      DrawCanvas.w = allWidth
      DrawCanvas.h = allHeight
      DrawCanvas.imgW = newWidth
      DrawCanvas.imgH = newHeight
      CreateCanvas(DrawCanvas.w, DrawCanvas.h)
      if (originData.pic) {
        DrawProductImage(originData.pic)
      }
      if (originData.avatar) {
        DrawAvaterImage(originData.avatar)
      }
      if (originData.name) {
        DrawName(originData.name)
      }
      if (originData.desc) {
        DrawDesc(originData.desc)
      }
      if (originData.price) {
        DrawPrice(originData.price)
      }
      if (originData.qrcode) {
        DrawQrCode(originData.qrcode)
      }
    })
  }
}
const LoadImage = (src: string) => {
  return new Promise((resolve, reject) => {
    uni.getImageInfo({
      src,
      success: (res: any) => {
        resolve(res)
      },
      fail: (res: any) => {
        reject(res)
      },
    })
  })
}
const LoadOuterDom = (dom: any) => {
  return new Promise((resolve, reject) => {
    uni
      .createSelectorQuery()
      .in(_this)
      .select(dom)
      .boundingClientRect((rect) => {
        resolve(rect)
      })
      .exec()
  })
}
const DrawCanvas = {
  w: 0,
  h: 0,
  imgW: 0,
  imgH: 0,
  lineSize: 0,
}
const CreateCanvas = (w: number, h: number) => {
  ctx = uni.createCanvasContext(canvasId, _this)
  ctx.fillStyle = '#FFFFFF'
  // 填充矩形区域，此处填充整个canvas
  ctx.fillRect(0, 0, w, h)
  cvsSize.value = { width: `${w}px`, height: `${h}px` }
}
const DrawProductImage = (img: any) => {
  uni.getImageInfo({
    src: img,
    success: (res: any) => {
      ctx.drawImage(res.path, grid.left, grid.top, DrawCanvas.imgW, DrawCanvas.imgH)
      DrawAllToCvs()
    },
  })
}
const DrawAvaterImage = (img: any) => {
  let radius = avatar.size / 2
  let rx: any = grid.left + radius
  let ry: any = grid.top + avatar.top + DrawCanvas.imgH + radius
  uni.getImageInfo({
    src: img,
    success: (res: any) => {
      ctx.arc(rx, ry, radius, 0, 2 * Math.PI)
      ctx.strokeStyle = '#FFFFFF' // 设置绘制圆形边框的颜色
      ctx.stroke() // 绘制出圆形，默认为黑色，可通过 ctx.strokeStyle = '#FFFFFF'， 设置想要的颜色
      ctx.clip()
      ctx.drawImage(res.path, rx - radius, ry - radius, avatar.size, avatar.size)
      // ctx.restore()
      DrawAllToCvs()
    },
  })
}
const DrawName = (text: any) => {
  ctx.font = name.size + 'px Arial'
  ctx.fillStyle = name.color
  ctx.setTextAlign('left')
  const content: any = text + ' ' + '为你推荐'
  const x: any = grid.left + avatar.size + name.left
  const y: any = grid.top + avatar.top + DrawCanvas.imgH + avatar.size / 2
  ctx.fillText(content, x, y)
  DrawAllToCvs()
}
const DrawDesc = (text: any) => {
  ctx.font = desc.size + 'px Arial'
  ctx.fillStyle = '#000000'
  ctx.setTextAlign('left')
  const fx: any = grid.left + desc.left
  const fy: any = grid.top + DrawCanvas.imgH + avatar.size + avatar.top + desc.top
  const size: any = Math.floor(desc.width / desc.size)
  for (let i = 0; i < DrawCanvas.lineSize; i++) {
    const start = i * size
    const end = (i + 1) * size
    const con = text.slice(start, end)
    ctx.fillText(con, fx, fy + (i + 1) * desc.line)
  }
  DrawAllToCvs()
}
const DrawPrice = (text: any) => {
  ctx.font = price.size + 'px Arial'
  ctx.fillStyle = price.color
  ctx.setTextAlign('left')
  const px: any = grid.left + price.left
  const py: any =
    grid.top +
    DrawCanvas.imgH +
    avatar.size +
    avatar.top +
    desc.top +
    price.top +
    price.size +
    desc.line * DrawCanvas.lineSize
  ctx.fillText('￥' + text, px, py)
  DrawAllToCvs()
}
const DrawQrCode = (pic: any) => {
  let x: any = DrawCanvas.w - qrcode.size - grid.right
  let y: any = grid.top + DrawCanvas.imgH + qrcode.top
  uni.getImageInfo({
    src: pic,
    success: (res: any) => {
      ctx.drawImage(res.path, x, y, qrcode.size, qrcode.size)
      const fy: any = y + qrcode.size + 10 + 12
      ctx.font = '12px Arial'
      ctx.fillStyle = '#666666'
      ctx.setTextAlign('center')
      ctx.fillText('长按识别二维码', x + qrcode.size / 2, fy)
      DrawAllToCvs()
    },
  })
}
let DrawedIndex = 0
const DrawAllToCvs = () => {
  DrawedIndex++
  if (drawIndex === DrawedIndex) {
    DrawedIndex = 0
    ctx.draw()
    CreateImage()
  }
}
const grid = {
  top: 10,
  left: 10,
  bottom: 10,
  right: 10,
}

const avatar = {
  size: 40,
  top: 10,
  left: 0,
}
const name = {
  size: 12,
  top: 10,
  left: 10,
  color: '#666666',
  line: 12,
}
const desc = {
  width: 200,
  size: 14,
  color: '#000000',
  top: 10,
  left: 0,
  line: 16,
}
const price = {
  size: 16,
  color: '#FF0000',
  top: 10,
  left: 0,
  line: 16,
}
const qrcode = {
  size: 88,
  top: 10,
  left: 0,
}
const CreateImage = () => {
  uni.canvasToTempFilePath(
    {
      x: 0,
      y: 0,
      width: DrawCanvas.w,
      height: DrawCanvas.h,
      canvasId: canvasId,
      success: function (res: any) {
        let path: any = res.tempFilePath
        if (platform === 'h5') {
          path = URL.createObjectURL(res.tempFilePath)
        }
        emits('success', {
          path,
        })
      },
      fail: function (res: any) {
        console.log(res)
      },
    },
    _this,
  )
}
// const drawQRCode = () => {
//   const qr = new UQRCode()
//   qr.data = info.qrData
//   qr.size = info.qrSize
//   qr.make()
//   const qrCtx = uni.createCanvasContext('QrCodeCanvas', _this)
//   qr.canvasContext = qrCtx
//   qr.drawCanvas()
//   console.log('drawQrCode')
//   uni.canvasToTempFilePath(
//     {
//       x: 0,
//       y: 0,
//       width: info.qrSize,
//       height: info.qrSize,
//       canvasId: 'QrCodeCanvas',
//       success: function (res: any) {
//         const x: any = info.width - info.qrSize
//         const y: any = info.imgH + info.qrTop
//         ctx.drawImage(res.tempFilePath, x, y, info.qrSize, info.qrSize)
//         const fy: any = x + info.btnTop
//         ctx.font = info.btnSize + 'px Arial'
//         ctx.fillStyle = '#666666'
//         ctx.setTextAlign('center')
//         ctx.fillText('长按识别二维码', x + info.qrSize / 2, fy)
//       },
//       fail: function (res: any) {
//         console.log(res)
//       },
//     },
//     _this,
//   )
// }
onUnmounted(() => {
  if (setTimeout$) {
    clearTimeout(setTimeout$)
  }
})
</script>

<style lang="scss"></style>
